//
//  NSString+MD5.m
//  sisitv_ios
//
//  Created by apple on 17/3/23.
//  Copyright © 2017年 JLXX--YZG. All rights reserved.
//

#import "NSString+JLXXMD5.h"
#import <CommonCrypto/CommonCrypto.h>

@implementation NSString (JLXXMD5)

+ (NSString *)stringToStreamWithRoom_id:(NSString *)room_id channel_crator:(NSString *)channel_crator timeString:(NSString *)timeString {
    if (!room_id) room_id = @"";
    if (!channel_crator) channel_crator = @"";
    if (!timeString) timeString = @"";
    // 加密盐
    NSString *saltStringMD5 = [self stringToMD5:@"weizibo"];
    
    NSString *room_idSaltMD5 = [self stringToSaltMD5:room_id salt:saltStringMD5];
    
    NSString *channel_cratorSaltMD5 = [self stringToSaltMD5:channel_crator salt:saltStringMD5];
    
    NSString *timeStringSaltMD5 = [self stringToSaltMD5:timeString salt:saltStringMD5];
    
    NSString *stringMD5 = [self stringToBubbleSort:[NSString stringWithFormat:@"%@%@%@", room_idSaltMD5, channel_cratorSaltMD5, timeStringSaltMD5]];
    
    NSString *string = [self stringToMD5:stringMD5] ;
    
    NSString *str = [string stringByReplacingOccurrencesOfString:@"b" withString:@"z"];
    
    return str;
}

+ (NSString *)stringToBubbleSort:(NSString *)string{
    NSMutableArray *arr_M = [NSMutableArray array];
    for (int i = 0; i < string.length; i ++) {
        [arr_M addObject:[string substringWithRange:NSMakeRange(i, 1)]];
    }
    for (int i = 0; i < arr_M.count; ++i) {
        for (int j = 0; j < arr_M.count-1; ++j) {
            if (arr_M[j] > arr_M[j+1]) {
                [arr_M exchangeObjectAtIndex:j withObjectAtIndex:j+1];
            }
        }
    }
    return [arr_M componentsJoinedByString:@""];
}

+ (NSString *)stringToSaltMD5:(NSString *)string salt:(NSString *)salt{
    NSString *stringMD5 = [self stringToMD5:string];
    
    NSString *stringSaltMD5 = [self stringToMD5:[NSString stringWithFormat:@"%@%@", stringMD5, salt]];
    
    return [stringSaltMD5 stringByReplacingOccurrencesOfString:@"a" withString:@"o"];
}

+ (NSString *)stringToMD5:(NSString *)str{
    //1.首先将字符串转换成UTF-8编码, 因为MD5加密是基于C语言的,所以要先把字符串转化成C语言的字符串
    const char *fooData = [str UTF8String];
    
    //2.然后创建一个字符串数组,接收MD5的值
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    
    //3.计算MD5的值, 这是官方封装好的加密方法:把我们输入的字符串转换成16进制的32位数,然后存储到result中
    CC_MD5(fooData, (CC_LONG)strlen(fooData), result);
    /**
     第一个参数:要加密的字符串
     第二个参数: 获取要加密字符串的长度
     第三个参数: 接收结果的数组
     */
    
    //4.创建一个字符串保存加密结果
    NSMutableString *saveResult = [NSMutableString string];
    
    //5.从result 数组中获取加密结果并放到 saveResult中
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [saveResult appendFormat:@"%02x", result[i]];
    }
    /*
     x表示十六进制，%02X  意思是不足两位将用0补齐，如果多余两位则不影响
     NSLog("%02X", 0x888);  //888
     NSLog("%02X", 0x4); //04
     */
    return saveResult;
}



@end
